package com.hwz.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hwz.gulimall.product.vo.Catalog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwz.common.utils.PageUtils;
import com.hwz.common.utils.Query;

import com.hwz.gulimall.product.dao.CategoryDao;
import com.hwz.gulimall.product.entity.CategoryEntity;
import com.hwz.gulimall.product.service.CategoryService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> list = this.list();
        //获取到所有的一级分类
        List<CategoryEntity> tree = list.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        //填充子分类
        setChildren(tree,list);

        return tree;
    }

    @Override
    public Long[] getCategoryPathById(Long catelogId) {
        ArrayList<Long> list = new ArrayList<>();
        list.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        while (categoryEntity != null && categoryEntity.getParentCid() != null && categoryEntity.getParentCid() != 0){
            list.add(categoryEntity.getParentCid());
            categoryEntity = this.getById(categoryEntity.getParentCid());
        }
        Collections.reverse(list);


        return list.toArray(new Long[0]);
    }


    //查询一级分类数据
    @Override
    @Cacheable(value = "catalogJson", key = "#root.methodName")
    public List<CategoryEntity> getFirstLevelCategories() {
        log.info("一级分类数据被缓存");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Override
    @Cacheable(value = "catalogJson", key = "#root.methodName")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        log.info("所有分类数据被缓存");
        List<CategoryEntity> tree = listWithTree();  //拿到完整的树形结构后进行数据封装
        HashMap<String, List<Catalog2Vo>> stringListHashMap = new HashMap<>();
        tree.stream().forEach(categoryLevel1 -> {
            ArrayList<Catalog2Vo> arrayList = new ArrayList<>();
            List<CategoryEntity> children1 = categoryLevel1.getChildren();
            children1.stream().forEach(item -> {
                Catalog2Vo catalog2Vo = new Catalog2Vo();
                catalog2Vo.setCatalog1Id(categoryLevel1.getCatId().toString());
                catalog2Vo.setId(item.getCatId().toString());
                catalog2Vo.setName(item.getName());

                List<CategoryEntity> children2 = item.getChildren();
                ArrayList<Catalog2Vo.Catalog3Vo> catalog3List = new ArrayList<>();
                children2.stream().forEach(item3 -> {
                    Catalog2Vo.Catalog3Vo catalog3 = new Catalog2Vo.Catalog3Vo();
                    catalog3.setCatalog2Id(item.getCatId().toString());
                    catalog3.setId(item3.getCatId().toString());
                    catalog3.setName(item3.getName());
                    catalog3List.add(catalog3);
                });
                catalog2Vo.setCatalog3List(catalog3List);

                arrayList.add(catalog2Vo);
            });
            stringListHashMap.put(categoryLevel1.getCatId().toString(),arrayList);
        });

        return stringListHashMap;
    }




//    @Cacheable(value = "catalogJson")
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        //1、查询redis有没有数据
        String jsonStr = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(jsonStr)){
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
//            String jsonString = JSON.toJSONString(catalogJsonFromDb);
//            redisTemplate.opsForValue().set("catalogJson",jsonString,10, TimeUnit.SECONDS);
            return catalogJsonFromDb;
        }
        //2、有数据，从redis中获取
        Map<String, List<Catalog2Vo>> stringListHashMap = JSON.parseObject(jsonStr, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });

        return stringListHashMap;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        RLock lock = redissonClient.getLock("catalogJsonLock");

        lock.lock();

        Map<String, List<Catalog2Vo>> res = null;
        try {
            res = getCatalogJsonFromDb();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }


        return res;
    }



    public  Map<String, List<Catalog2Vo>> getCatalogJsonFromDb() {
            //再次判断缓存是否有数据，如果有直接返回
            String jsonStr = redisTemplate.opsForValue().get("catalogJson");
            if (!StringUtils.isEmpty(jsonStr)){
                Map<String, List<Catalog2Vo>> stringListHashMap = JSON.parseObject(jsonStr, new TypeReference<Map<String, List<Catalog2Vo>>>() {
                });
                return stringListHashMap;
            }

            //如果没有再去查询db
            List<CategoryEntity> tree = listWithTree();
            HashMap<String, List<Catalog2Vo>> stringListHashMap = new HashMap<>();
            tree.stream().forEach(categoryLevel1 -> {
                ArrayList<Catalog2Vo> arrayList = new ArrayList<>();
                List<CategoryEntity> children1 = categoryLevel1.getChildren();
                children1.stream().forEach(item -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo();
                    catalog2Vo.setCatalog1Id(categoryLevel1.getCatId().toString());
                    catalog2Vo.setId(item.getCatId().toString());
                    catalog2Vo.setName(item.getName());

                    List<CategoryEntity> children2 = item.getChildren();
                    ArrayList<Catalog2Vo.Catalog3Vo> catalog3List = new ArrayList<>();
                    children2.stream().forEach(item3 -> {
                        Catalog2Vo.Catalog3Vo catalog3 = new Catalog2Vo.Catalog3Vo();
                        catalog3.setCatalog2Id(item.getCatId().toString());
                        catalog3.setId(item3.getCatId().toString());
                        catalog3.setName(item3.getName());
                        catalog3List.add(catalog3);
                    });
                    catalog2Vo.setCatalog3List(catalog3List);

                    arrayList.add(catalog2Vo);
                });
                stringListHashMap.put(categoryLevel1.getCatId().toString(),arrayList);
            });
            //将数据放回redis
            String jsonString = JSON.toJSONString(stringListHashMap);
            redisTemplate.opsForValue().set("catalogJson",jsonString,10, TimeUnit.SECONDS);


            return stringListHashMap;
    }

    public void setChildren(List<CategoryEntity> parent,List<CategoryEntity> all){
        for (CategoryEntity entity : parent) {
            //找到当前父类下的所有子分类
            List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == entity.getCatId())
                    .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
            entity.setChildren(children);

            //递归tianc
            setChildren(children,all);
        }
    }


    @Cacheable(value = "name")
    public String hello(String  name){
        log.info(name + "已经被缓存");
        return "hello" + name;
    }

}